package controller;

import service.BookService;
import service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取书籍ID
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);

        // 删除书籍
        if (bookService.deleteBook(id)) {
            // 删除成功
            request.getSession().setAttribute("deleteSuccess", "true");
            response.sendRedirect(request.getContextPath() + "/bookList");
        } else {
            // 删除失败
            request.setAttribute("errorMsg", "删除书籍失败");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}